const Base = require('./base.js');

module.exports = class extends Base {
  // 根据动作查找记录
  async getAllRecordByActionIdAction() {
    var value = this.get();
    var openId = value.openId;
    var actionId = value.actionId;
    // 获取trainId后去查询其他记录

    var trainRecord = await this.model('train')
      .field('trainId')
      .order('createTime DESC')
      .select();

    // 所有递减项的列表
    var decreaseItemResult = await this.model('decrease_item').alias('decreaseItem').field('`decreaseItem`.*')
      .join([{
        table: 'decrease',
        as: 'decrease',
        on: ['`decrease`.`decreaseId`', '`decreaseItem`.`decreaseId`']
      }])
      .where({'train.openId': openId, 'train.actionId': actionId})
      .join([{
        table: 'train',
        as: 'train',
        on: ['`train`.`trainId`', '`decrease`.`trainId`']
      }])
      .where({'train.openId': openId, 'train.actionId': actionId})
      .select();
    var decreaseResult = await this.model('decrease').alias('common').field('`common`.*')
      .join([{
        table: 'train',
        as: 'train',
        on: ['`train`.`trainId`', '`common`.`trainId`']
      }])
      .where({'train.openId': openId, 'train.actionId': actionId})
      .select();
    decreaseResult = JSON.parse(JSON.stringify(decreaseResult));
    decreaseItemResult = JSON.parse(JSON.stringify(decreaseItemResult));

    for (let i = 0; i < decreaseResult.length; i++) {
      let list = [], k = 0;
      const item = decreaseResult[i];
      for (let j = 0; j < decreaseItemResult.length; j++) {
        if (decreaseResult[i].decreaseId === decreaseItemResult[j].decreaseId) {
          list[k++] = decreaseItemResult[j];
        }
      }
      item.list = list;
      decreaseResult[i] = item;
    }

    var commonResult = await this.model('common').alias('common').field('`common`.*')
      .join([{
        table: 'train',
        as: 'train',
        on: ['`train`.`trainId`', '`common`.`trainId`']
      }])
      .where({'train.openId': openId, 'train.actionId': actionId})
      .select();

    var fixationResult = await this.model('fixation').alias('common').field('`common`.*')
      .join([{
        table: 'train',
        as: 'train',
        on: ['`train`.`trainId`', '`common`.`trainId`']
      }])
      .where({'train.openId': openId, 'train.actionId': actionId})
      .select();
    var superResult = await this.model('super').alias('common').field('`common`.*')
      .join([{
        table: 'train',
        as: 'train',
        on: ['`train`.`trainId`', '`common`.`trainId`']
      }])
      .where({'train.openId': openId, 'train.actionId': actionId})
      .select();

    // console.log('decreaseItemResult: ', decreaseItemResult);
    trainRecord = JSON.parse(JSON.stringify(trainRecord));
    commonResult = JSON.parse(JSON.stringify(commonResult));
    fixationResult = JSON.parse(JSON.stringify(fixationResult));
    superResult = JSON.parse(JSON.stringify(superResult));

    const newArr = [];
    for (let i = 0; i < trainRecord.length; i++) {
      const arrItem = [];
      for (let j = 0; j < commonResult.length; j++) {
        if (trainRecord[i].trainId === commonResult[j].trainId) {
          arrItem.push(commonResult[j]);
        }
      }
      for (let j = 0; j < decreaseResult.length; j++) {
        if (trainRecord[i].trainId === decreaseResult[j].trainId) {
          arrItem.push(decreaseResult[j]);
        }
      }
      for (let j = 0; j < fixationResult.length; j++) {
        if (trainRecord[i].trainId === fixationResult[j].trainId) {
          arrItem.push(fixationResult[j]);
        }
      }
      for (let j = 0; j < superResult.length; j++) {
        if (trainRecord[i].trainId === superResult[j].trainId) {
          arrItem.push(superResult[j]);
        }
      }

      newArr.push(arrItem);
    }

    for (let i = 0; i < newArr.length; i++) {
      if (newArr[i].length !== 1) {
        for (let j = i + 1; j < newArr[i].length; j++) {
          if (newArr[i].index > newArr[j].index) {
            const t = newArr[i];
            newArr[i] = newArr[j];
            newArr[j] = t;
          }
        }
      }
    }
    this.success(newArr);
  }

  async getLastRecordAction() {
    var value = this.get();
    var result = await this.model('train')
      .where({openId: value.openId})
      .order('createTime DESC')
      .limit(1)
      .select();
    if (think.isEmpty(result)) {
      this.fail('no_train_record');
    } else {
      this.success(result);
    }
  }

  async addRecordAction() {
    const value = this.get();
    let {openId, actionId, record, name, trainId, recordIndex} = value;

    record = JSON.parse(record);
    console.log('record: ', record);
    if (trainId == -1) {
      trainId = new Date().getTime() + openId.slice(0, 5);
      const createTime = new Date().getTime();
      await this.model('train')
        .where({createTime: createTime, trainId: trainId})
        .thenAdd({
          createTime: createTime,
          trainId: trainId,
          actionId: actionId,
          openId: openId
        });
    }
    if (name === 'decrease') {
      const decreaseId = Math.random().toString(16).substring(2, 12);
      await this.model(name)
        .where({
          decreaseId: decreaseId,
          trainId: trainId,
          index: recordIndex
        })
        .thenAdd({
          decreaseId: decreaseId,
          trainId: trainId,
          index: recordIndex,
          remark: record.remark
        });

      console.log('record: ', record, typeof record);
      for (let i = 0; i < record.data.length; i++) {
        await this.model('decrease_item')
          .add({
            decreaseId: decreaseId,
            times: record.data[i].times,
            index: i + 1,
            kilogram: record.data[i].kilogram
          });
      }
    } else {
      record.trainId = trainId;
      record.index = recordIndex;
      await this.model(name)
        .where(record)
        .thenAdd(record);
    }

    const result = {
    };
    this.success(trainId);
  }
};
